# -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>

# <codecell>

import Image

# <codecell>

import matplotlib.pyplot as plt

# <codecell>

orig_img = Image.open("test2.jpg")

# <codecell>

imshow(orig_img)

# <codecell>

def stretch_hist_RGB(img):
    in_channels = img.split()
    out_channels = []
    for ch in in_channels:
        ch_data = list(ch.getdata())
        ch_min, ch_max = min(ch_data), max(ch_data)
        ch_out = ch.point(lambda x: (255.0 * (x - ch_min))/(ch_max - ch_min))
        out_channels.append(ch_out)
    img_out = Image.merge("RGB", out_channels)
    return img_out

# <codecell>

def stretch_hist_Y(img):
    img_YCbCr = img.convert("YCbCr")
    Y, Cb, Cr = img_YCbCr.split()
    ch_data = list(Y.getdata())
    ch_min, ch_max = min(ch_data), max(ch_data)
    Y_out = Y.point(lambda x: (255.0 * (x - ch_min))/(ch_max - ch_min))
    img_out = Image.merge("YCbCr", (Y_out, Cb, Cr)).convert("RGB")
    return img_out

# <codecell>

def plot_hist_RGB(img):
    fig, axes = plt.subplots(1, 3, figsize=(16, 4), dpi=100)

    R, G, B = img.split()
    
    hist_R = R.histogram()
    hist_G = G.histogram()
    hist_B = B.histogram()
    
    for x in xrange(0, 255):
        axes[0].bar(x, hist_R[x])
        axes[0].set_ylim([0, 255])
        axes[0].set_title("R")

        axes[1].bar(x, hist_G[x])
        axes[1].set_ylim([0, 255])
        axes[1].set_title("G")

        axes[2].bar(x, hist_B[x])
        axes[2].set_ylim([0, 255])
        axes[2].set_title("B")
plt.show()

# <codecell>

img_stretch_RGB = stretch_hist_RGB(orig_img)

# <codecell>

imshow(img_stretch_RGB)
img_stretch_RGB.save("img_stretch_RGB.png")

# <codecell>

img_stretch_Y = stretch_hist_Y(orig_img)

# <codecell>

imshow(img_stretch_Y)
img_stretch_Y.save("img_stretch_Y.png")

# <codecell>

plot_hist_RGB(orig_img)

# <codecell>

plot_hist_RGB(img_stretch_RGB)

# <codecell>

plot_hist_RGB(img_stretch_Y)

# <codecell>


